package com.javacv.plus.core.processor;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 处理器责任链
 * 
 * @param <T> 处理器类型
 * @param <R> 结果类型
 */
@Slf4j
public class ProcessorChain<T, R> {

    private final List<ProcessorStep<T, R>> steps = new ArrayList<>();

    /**
     * 添加处理步骤
     */
    public ProcessorChain<T, R> addStep(ProcessorStep<T, R> step) {
        if (step != null && step.isEnabled()) {
            steps.add(step);
            // 按优先级排序
            steps.sort(Comparator.comparing(ProcessorStep::getPriority));
            log.debug("添加处理步骤: {}, 优先级: {}", step.getStepName(), step.getPriority());
        }
        return this;
    }

    /**
     * 执行处理链
     */
    public R execute(T processor, ProcessorContext context) throws Exception {
        R result = null;
        
        for (ProcessorStep<T, R> step : steps) {
            log.debug("执行处理步骤: {}", step.getStepName());
            
            long startTime = System.currentTimeMillis();
            try {
                result = step.execute(processor, context);
                long duration = System.currentTimeMillis() - startTime;
                log.debug("处理步骤 {} 执行完成，耗时: {}ms", step.getStepName(), duration);
                
                // 更新上下文
                context.setLastResult(result);
                
            } catch (Exception e) {
                log.error("处理步骤 {} 执行失败", step.getStepName(), e);
                throw e;
            }
        }
        
        return result;
    }

    /**
     * 获取步骤数量
     */
    public int getStepCount() {
        return steps.size();
    }

    /**
     * 清空所有步骤
     */
    public void clear() {
        steps.clear();
    }

    /**
     * 获取所有步骤名称
     */
    public List<String> getStepNames() {
        List<String> names = new ArrayList<>();
        for (ProcessorStep<T, R> step : steps) {
            names.add(step.getStepName());
        }
        return names;
    }
} 